﻿using System.Net.Sockets;
using Letter.Net.Session;

namespace Letter.Net.Tcp;

abstract class ATcpHost<TTransportOptions, TFeatureOptions> : AHost<TTransportOptions, TFeatureOptions>
    where TTransportOptions : ATcpTransportOptions, new()
    where TFeatureOptions : class, IFeatureOptions, new()
{
    protected delegate ISession CreateTransportDelegate(Socket socket, IChannelSettings settings, AConnection connection);
    
    private static ISession PooledSnderTransport(Socket socket, IChannelSettings settings, AConnection connection)
    {
        var setting = new TransportSettings(
                                            settings.Scheduler, 
                                            settings.MemoryPool,
                                            settings.InputOptions,
                                            settings.OutputOptions
                                            );

        return SessionProvider.CreateTcpSessionFromSenderPool(socket, setting, connection);
    }

    private static ISession SolelySnderTransport(Socket socket, IChannelSettings settings, AConnection connection)
    {
        var setting = new TransportSettings(
            settings.Scheduler, 
            settings.MemoryPool,
            settings.InputOptions,
            settings.OutputOptions
        );
        
        return SessionProvider.CreateTcpSessionFromSenderSole(socket, setting, connection);
    }

    protected ATcpHost(string name) : base(name)
    {
    }

    protected CreateTransportDelegate transportFactory;

    public override void Build()
    {
        base.Build();

        this.transportFactory = this.transportOptions.PooledSnder ? PooledSnderTransport : SolelySnderTransport;
    }
}
